package com.thexb.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thexb.common.Result;
import com.thexb.sys.entity.Role;
import com.thexb.sys.entity.User;
import com.thexb.sys.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author thexb
 * @since 2023-04-04
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @GetMapping("/list")
    public Result<Map<String, Object>> getUserList(@RequestParam(value = "role_name", required = false) String role_name,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(role_name), Role::getRoleName, role_name);
        queryWrapper.orderByDesc(Role::getRoleId);

        Page<Role> page = new Page<>(pageNo, pageSize);
        roleService.page(page, queryWrapper);

        HashMap<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("rows", page.getRecords());
        return Result.success(map);
    }
    @GetMapping("/all")
    public Result<List<Role>> getUserList() {
        List<Role> list = this.roleService.list();
        return Result.success(list);
    }
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getUserById(@PathVariable("id") int id) {
        Role role = roleService.getRoleById(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("role", role);
        return Result.success(map, "获取角色成功");
    }
    @PutMapping
    public Result<Map<String, Object>> updateUser(@RequestBody Role role) {
        roleService.updateRole(role);
        return Result.success(null, "修改角色成功");
    }
    @PostMapping
    public Result<Map<String, Object>> addUser(@RequestBody Role role) {
        // roleService.save(role);
        roleService.addRole(role);
        return Result.success(null, "新增角色成功");
    }
    @DeleteMapping("/{id}")
    public Result<Map<String, Object>> removeUserById(@PathVariable("id") int id) {
        roleService.removeRole(id);
        return Result.success(null, "删除角色成功");
    }
}
